package servlet.events;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bundle.ErrorsBundleKey;

import util.SimpleMD5;

import dao.DAOFactory;
import dao.interfaces.IUserDAO;

import model.User;

public class LoginHandler extends EventHandler {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if (validateForm(request)) {
			String login = request.getParameter("login");
			String password = ""; 
			try {
				password = SimpleMD5.encrypt(request.getParameter("password"));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			
			IUserDAO<User> userDAO = DAOFactory.getUserDAO();
			
			User user = userDAO.authenticateUser(login, password);
			
			if (user != null) {
				request.setAttribute("status", "ok");
				
				//set user session
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				
				//update the numbers of authenticated users
				ServletContext application = request.getSession().getServletContext();
				
				Integer authenticatedUserCount = (Integer) application.getAttribute("authenticatedUserCount");
				
				if (authenticatedUserCount == null) {
					authenticatedUserCount = 0;
				}
				application.setAttribute("authenticatedUserCount", ++authenticatedUserCount);
			}
			else {
				request.setAttribute("status", "error");
				setErrors(ErrorsBundleKey.UserErrorBundleKey.LOGIN_FAIL, request);
			}
		}
		//forward to login.jsp
		forward(urlBundle.getString("LOGIN_URL"), request, response);
	}
	
	private boolean validateForm(HttpServletRequest request) {
		int i = 0;
		
		if (request.getParameter("login") == null || request.getParameter("login").trim().equals("")) {
			setErrors(ErrorsBundleKey.UserErrorBundleKey.LOGIN_NOT_NULL, request);
			i++;
		}
		
		if (request.getParameter("password") == null || request.getParameter("password").equals("")) { //space is ok
			setErrors(ErrorsBundleKey.UserErrorBundleKey.PASSWORD_NOT_NULL, request);
			i++;
		}
		
		if (i > 0)
			return false;
		
		return true;
	}
}
